import Post from '@/model/Post';
import Link from '@/model/Link';
import moment from 'moment';
import { v4 as uuid } from 'uuid';
import config from '@/config';
import makeDir from 'make-dir';
import fs from 'fs';

class ContentController {
  async getPostList (ctx) {
    // 测试数据添加
    // const post = new Post({
    //   title: 'test title 222',
    //   content: 'test content',
    //   catalog: 'notice',
    //   fav: 40,
    //   isEnd: '0',
    //   reads: '1',
    //   answer: '100',
    //   status: '1',
    //   isTop: '0',
    //   sort: '0',
    //   tags: [{
    //     name: '划水',
    //     class: ''
    //   }]
    // });
    // await post.save();

    const query = ctx.query;
    const page = query.page ? parseInt(query.page) : 0;
    const limit = query.limit ? parseInt(query.limit) : 0;
    const sort = query.sort ? query.sort : 'created';
    const options = {};

    if (query.catalog) options.catalog = query.catalog;
    if (query.isTop) options.isTop = query.isTop;
    if (query.isEnd) options.isEnd = query.isEnd;
    if (query.status) options.status = query.status;
    if (query.tag) options.tags = { $elemMatch: { name: query.tag } };

    const list = await Post.getList(options, sort, page, limit);

    ctx.body = {
      code: 200,
      data: list,
      msg: '获取文章列表成功'
    };
  }

  async getLinksList (ctx) {
    // 测试数据添加
    // const link = new Link({
    //   title: '掘金',
    //   link: 'https://juejin.cn',
    //   type: 'link'
    // });
    // await link.save();

    const list = await Link.find({ type: 'link' });

    ctx.body = {
      code: 200,
      data: list,
      msg: '获取友情链接列表成功'
    };
  }

  async getTipsList (ctx) {
    // 测试数据添加
    // const tip = new Link({
    //   title: 'myKSong',
    //   link: 'https://kg.qq.com/node/personal?uid=6b9e9e87252e378f',
    //   type: 'tip'
    // });
    // await tip.save();

    const list = await Link.find({ type: 'tip' });

    ctx.body = {
      code: 200,
      data: list,
      msg: '获取温馨链接列表成功'
    };
  }

  async getHotList (ctx) {
    const list = await Post.getHotList();

    ctx.body = {
      code: 200,
      data: list,
      msg: '获取热议文章列表成功'
    };
  }

  async getTopList (ctx) {
    const list = await Post.getTopList();

    ctx.body = {
      code: 200,
      data: list,
      msg: '获取置顶文章列表成功'
    };
  }

  async uploadImg (ctx) {
    // files是获取请求中formData信息，file是指定的图片键名
    const file = ctx.request.files.file;

    const ext = file.name.split('.').pop();
    const dir = `${config.uploadPath}/${moment().format('YYMMDD')}`;

    // 判断文件路径是否存在，不存在则创建
    await makeDir(dir);

    // 存储文件到指定的路径
    const filename = `${uuid()}.${ext}`;
    const destPath = `${dir}/${filename}`;
    // file.path 为临时存储路径
    const reader = fs.createReadStream(file.path)
    // 设置chunk大小
    // const reader = fs.createReadStream(file.path, {
    //   hightWaterMark: 1 * 1024
    // });
    const upStream = fs.createWriteStream(destPath);
    // 返回给前端的资源路径
    const filePath = `/${moment().format('YYMMDD')}/${filename}`;

    // 存储文件方法1
    reader.pipe(upStream);

    // 存储文件方法2
    // 获取文章的总长度
    // const stat = fs.statSync(file.path);

    // let totalLength = 0;
    // reader.on('data', (chunk) => {
    //   totalLength += chunk.length;
    //   console.log(totalLength);
    //   // 这里会根据readStream创建时设置的chunk大小，每到达该大小的时候进行一次暂停，进行数据处理，如上传进度控制等
    //   if (upStream.write(chunk) === false) {
    //     reader.pause();
    //   }
    // });
    // reader.on('drain', () => {
    //   reader.resume();
    // });
    // reader.on('end', () => {
    //   upStream.end();
    // });

    ctx.body = {
      code: 200,
      data: filePath,
      msg: '文件上传成功'
    };
  }
}

export default new ContentController();
